import { Inject, Provide } from '@midwayjs/core';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, Not, In } from 'typeorm';
import { StudentStudentEntity } from '../entity/student';
import { AppointmentInfoEntity } from '../../appointment/entity/info';
import { DictInfoEntity } from "../../dict/entity/info";
import { BaseSysUserEntity } from '../../base/entity/sys/user';
import { DoctorInfoEntity } from '../../doctor/entity/info';
// import { QRCode } from 'qrcode';

/**
 * 学生信息
 */
@Provide()
export class StudentStudentService extends BaseService {
  @InjectEntityModel(StudentStudentEntity)
  studentStudentEntity: Repository<StudentStudentEntity>;

  @InjectEntityModel(AppointmentInfoEntity)
  appointmentInfoEntity: Repository<AppointmentInfoEntity>;

  @InjectEntityModel(DictInfoEntity)
  dictInfoEntity: Repository<DictInfoEntity>;

  @InjectEntityModel(BaseSysUserEntity)
  baseSysUserEntity: Repository<BaseSysUserEntity>;

  @InjectEntityModel(DoctorInfoEntity)
  doctorInfoEntity: Repository<DoctorInfoEntity>;
  /**
   * 获取学生列表
   */

  async page(query, options) {
    // const result = await super.page(query, options);
    // console.log(query, options);
    if (!query.showAppoint) {
      const returnPage = await super.page(query, options);
      return returnPage;
    }
    if (query.allStudent && query.allStudent === 1) {
      if (query.hasOwnProperty('sales')) {
          delete query.sales;
      }
    }
    let result = null;
    let pagination = null
    if (!query.appointmentStatus) {
      result = await super.page(query, options);
      pagination = result.pagination;
    } else {
      result = await super.page({
        ...query,
        page: 1,
        size: 10000
      }, options);
    }
    // 批量查询所有学生的最新预约信息
    const studentIds = result.list.map(student => student.id);
    const appointments = await this.appointmentInfoEntity.find({
      where: { 
        studentId: In(studentIds),
        // appointmentStatus: Not(In([2, 4]))
      },
      order: { appointmentTime: 'DESC' }
    });
    const shops = await this.dictInfoEntity.find({ where: { typeId: 27 } });
    const shopMap = shops.reduce((acc, shop) => { 
      acc[shop.id] = shop; 
      return acc; 
    }, {} as Record<number, any>);
    // 获取每个学员的最新预约信息
    // 如果没有预约筛选则不需要查询所有学员

    const filteredList = [];
    for (const student of result.list) {
      // const appointment = await this.appointmentInfoEntity.findOne({
      //   where: { studentId: student.id, appointmentStatus: Not(2) },
      //   order: { appointmentTime: 'DESC' }
      // });
      // 查找该学生最新的预约
      const appointment = appointments.find(a => a.studentId === student.id);
      
      // 根据 appoint 参数筛选数据
      if (query.appoint !== undefined) {
        if ((query.appoint === 1 && !appointment) || (query.appoint === 0 && appointment)) {
          continue;
        }
      }

      if (query.appointmentStatus!== undefined) {
        if (query.appointmentStatus !== appointment?.appointmentStatus) {
          continue;
        }
      }

      // 根据跟进状态筛选数据
      if (query.flowStatus!== undefined) {
        if (!query.flowStatus.includes(student?.flowStatus)) {
          continue;
        }
      }
      // 选项
      const appointmentStatus = [
        { label: '已预约', value: 0 },
        { label: '已到店', value: 1 },
        { label: '已改约', value: 2 },
        { label: '已过期', value: 3 },
        { label: '已取消', value: 4 }
      ];
      student.appointment = appointment || null;
      student.appointmentText = '';
      student.salesAppointmentText = '';
      student.appointmentDate = '';
      student.appointmentShop = '';

      if (appointment) {
        const status = appointmentStatus.find(item => item.value === appointment.appointmentStatus);
        student.appointmentText = status ? status.label : '未知状态';
        const date = new Date(appointment.appointmentTime);
        // 需要加上年份
        student.appointmentDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
        // 查询门店名称
        const shop = shopMap[appointment.shopId];
        student.appointmentShop = shop ? shop.name : '';
      }
      student.appointmentTextShop = student.appointmentText;
      student.appointmentShopShop = student.appointmentShop;
      student.appointmentDateShop = student.appointmentDate;
      filteredList.push(student);
    }

    if (!query.appointmentStatus) {
      return  {
        list: filteredList,
        pagination: pagination
      }
    } else {
        // 手动进行分页处理
        const pageSize = query.size || 20;
        const page = query.page || 1;
        const total = filteredList.length;
        const start = (page - 1) * pageSize;
        const end = start + pageSize;
        
        return {
          list: filteredList.slice(start, end),
          pagination: {
            page: page,
            size: pageSize,
            total: total
          }
        };
    }
    
    // console.log(result.list.length, filteredList.length);
    // console.log(pageObj);
    // return pageObj;
    // 更新结果
    // result.list = filteredList;
    // result.pagination.total = filteredList.length;
    // return result;
  }

  async add(param) {
    // 校验上传的手机号，自动清除空格和校验手机号格式
    if (param.phone) {
      param.phone = param.phone.replace(/\s/g, '');
      if (!/^1[3456789]\d{9}$/.test(param.phone)) {
        throw new CoolCommException('手机号格式错误');
      }
      // 手机号和姓名都一样则不能录入
      const existStudent = await this.studentStudentEntity.findOne({
        where: { phone: param.phone, name: param.name }
      });
      if (existStudent) {
        throw new CoolCommException('该手机号和姓名已存在');
      }
    }
    const result = await super.add(param);
    
    return result;
  }

  /**
   * 通过学员ID查询销售的二维码信息
   */
  async getSalesQrCode(studentId: number) {
    // 处理studentId，去掉开头的100
    const actualStudentId = Number(String(studentId).substring(3));
    // 查询学员信息
    const student = await this.studentStudentEntity.findOne({
      where: { id: actualStudentId }
    });
    if (!student) {
      return null;
    }
    // 如果actualStudentId是8047，则随机显示sales为13或者sales为7的二维码
    let salesId = student.sales;
    if (actualStudentId === 8047) {
        const randomSales = Math.floor(Math.random() * 2);
        if (randomSales === 0) {
          salesId = 13;
        } else {
          salesId = 7;
        }
    }

    // 查询销售信息
    const sales = await this.baseSysUserEntity.findOne({
      where: { id: salesId }
    });
    if (!sales) {
      return null;
    }
    return sales.wechatQRCode;
  }

  /**
   * 手机号返回学员列表
   */
  async getStudentByPhone(phone: string) {
    try {
      // 查找所有学生信息
      const students = await this.studentStudentEntity.find(
        {
          where: {
            phone: phone
          }
        }
      );
      // 将学员的ID和姓名组合成数组
      const studentList = students.map(student => ({
        id: student.id,
        name: student.name
      }));
      return studentList;
    } catch (error) {
      console.error('获取学生信息失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户最近的预约信息
   */
  async getLatestAppointment(studentId: number) {
    try {
      let result = {
        month: '',
        day: '',
        time: '',
        doctorName: '',
        shopName: '',
      }
      // 查找该学生的最新预约
      const appointment = await this.appointmentInfoEntity.findOne({
        where: { studentId: studentId, appointmentStatus: Not(In([2, 4])) },
        order: { appointmentTime: 'DESC' }
      });
      if (appointment) {
        const monthAbbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        result.month = monthAbbr[appointment.appointmentTime.getMonth()];
        result.day = String(appointment.appointmentTime.getDate()).padStart(2, '0');
        result.time = `${String(appointment.appointmentTime.getHours()).padStart(2, '0')}:${String(appointment.appointmentTime.getMinutes()).padStart(2, '0')}`;
        // 查询门店名称
        const shop = await this.dictInfoEntity.findOne({
          where: { id: appointment.shopId }
        });
        result.shopName = shop? shop.name : '';
        const doctor = await this.doctorInfoEntity.findOne({
          where: { id: appointment.doctorId }
        });
        result.doctorName = doctor? doctor.name : '';
      }
      return result;
    } catch (error) {
      console.error('获取用户最近的预约信息失败:', error);
      throw error;
    }
  }

  /**
   * 生成个人信息二维码
   */
  async getPersonalQrCode(studentId: number) {
    try {
      // 处理studentId，去掉开头的100
      const actualStudentId = studentId;
      // 查询学员信息
      const student = await this.studentStudentEntity.findOne({
        where: { id: actualStudentId }
      });

      if (!student) {
        throw new Error('未找到该学员信息');
      }
      // <<,32,林30,2012/10/31,M,13112345708,一年级一班,>>
      // 拼接字符串
      const birthday = student.birthday ? new Date(student.birthday).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '/') : '';
      const gender = student.gender === 0? 'M' : 'F';
      const shop = await this.dictInfoEntity.findOne({
        where: { id: student.shop }
      });
      const shopName = shop? shop.name : '';
      const qrContent = `<<,${actualStudentId},${student.name},${birthday},${gender},${student.phone},${shopName},>>`;
      const QRCode = require('qrcode');
      // 检查 QRCode 是否正确导入
      if (!QRCode) {
        throw new Error('QRCode 对象未正确导入');
      }

      // 生成二维码
      const qrCodeDataUrl = await QRCode.toDataURL(qrContent);

      return {
        qrCodeDataUrl: qrCodeDataUrl,
        studentId: actualStudentId,
        name: student.name,
        birthday: birthday,
        gender: gender,
        phone: student.phone,
        shop: shopName,
        text: `${actualStudentId},${student.name},${birthday},${gender},${student.phone},${shopName}`,
      }
    } catch (error) {
      console.error('生成个人信息二维码时出错:', error);
      throw error;
    }
  }
}
